<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Mytask extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }
    /**
     * 获取我的四个类型任务的数量
     */
    public function getFourTaskNum()
    {
        extract(input());
        $where = array();
        $where['tu_user_id'] = $user_id;
        $field = 'task_id';//最后一个是下架时间
        //进行中
        $where['task_status'] = array('in', '2,3');//任务进行中或者结束
        $where['tu_status'] = array('in', '3,4');//我拒绝或进行中
        $data = array();
        $data['one'] = Db::table('up_task_user')->alias('tu')
            ->join('up_task t', 'tu.tu_task_id=t.task_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->count();
        $where['task_status'] = array('in', '2,3');//任务进行中或者结束
        $where['tu_status'] = 1;//我待审核
        $data['two'] = Db::table('up_task_user')->alias('tu')
            ->join('up_task t', 'tu.tu_task_id=t.task_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->count();
        $where['task_status'] = array('in', '2,3,4');//任务进行中或者结束或者下架
        $where['tu_status'] = array('in', '2,5,7');//我完成、结束、超时
        $data['three'] = Db::table('up_task_user')->alias('tu')
            ->join('up_task t', 'tu.tu_task_id=t.task_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->count();
        $where['task_status'] = array('in', '2,3');//任务进行中或者结束
        $where['tu_status'] = 6;//我取消
        $data['four'] = Db::table('up_task_user')->alias('tu')
            ->join('up_task t', 'tu.tu_task_id=t.task_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->count();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取我的任务
     */
    public function myTasks(){
        extract(input());
        $where = array();
        $where['tu_task_active'] = ['in','1,2'];
        if(isset($super) && $super == 2){
            $where['tu_task_active'] = 3;
        }
        $where['tu_user_id'] = $user_id;
        $order = 'tu_receive_time DESC';
        $field = 'task_id,task_type,task_name,task_image,task_num,task_price,task_get_num,task_status';
        $field .= ',task_starttime,task_endtime,task_update_time';//最后一个是下架时间
        $field .= ',tu_id,tu_receive_time,tu_submit_time,tu_cancel_time,tu_do_time,tu_reason,tu_status,tu_have_not,tu_real_time';//如果是超时的，最后一个往后加两天既是超时时间
        $field .= ',tu_super_yes,tu_task_active';// 达人任务，tu_status为4且此值为1，需要操作接受或者不接受
        if($type == 1){
            //进行中
            $where['task_status'] = array('in','2,3');//任务进行中或者结束
            $where['tu_status'] = array('in','3,4');//我拒绝或进行中
        }elseif ($type == 2){
            $where['task_status'] = array('in','2,3');//任务进行中或者结束
            $where['tu_status'] = 1;//我待审核
        }elseif ($type == 3){
            //为4就是已下架，else 257
            $where['task_status'] = array('in','2,3,4');//任务进行中或者结束或者下架
            $where['tu_status'] = array('in','2,5,7');//我完成、结束、超时
        }else{
            $where['task_status'] = array('in','2,3');//任务进行中或者结束
            $where['tu_status'] = 6;//我取消
        }
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where($where)
            ->field($field)
            ->order($order)
            ->page($page,10)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 达人任务：接受
     */
    public function superTasksReceive(){
        extract(input());
        $tasktype = ['error','下载','求赞求粉','问卷','投票','视频','分享'];
        $where = array();
        $where['tu_id'] = $tu_id;
        $field = 'tu_task_id,task_type,task_status,task_lock,task_price,task_super_first_money,tu_user_id,tu_s_id,tu_status,tu_task_active';
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where($where)
            ->field($field)
            ->find();
        if($data['tu_status'] != 4 || $data['tu_task_active'] != 3 || $data['task_status'] >= 3){
            return json(['status'=>100,'msg'=>'只有进行中的待接受的达人任务才可以操作']);
        }else{
            // 启动事务
            Db::startTrans();
            try{// 提交事务
                $update = [
                    'tu_super_yes' => 2,
                    'tu_real_time' => date('Y-m-d H:i:s')
                ];
                Db::table('up_task_user')
                    ->where($where)
                    ->update($update);
                if($data['task_lock'] == 1){
                    Db::name('u_user')->where('user_id',$data['tu_user_id'])->setInc('user_super_no',$data['task_super_first_money']);
                }else{
                    Db::name('u_user')->where('user_id',$data['tu_user_id'])->setDec ('user_week_money',$data['task_super_first_money']);
                    Db::name('u_user')->where('user_id',$data['tu_user_id'])->setDec ('user_month_money',$data['task_super_first_money']);
                    Db::name('u_user')->where('user_id',$data['tu_user_id'])->setDec ('user_all_money',$data['task_super_first_money']);
                }
                Db::table('up_task')->where('task_id',$data['tu_task_id'])->setInc('task_get_num');
                Db::table('up_task')->where('task_id',$data['tu_task_id'])->setField('task_status',2);
                allInDetail($data['tu_user_id'],1,$tasktype[$data['task_type']].'达人任务',$data['task_super_first_money'],$data['task_type'],3);
                Db::commit();
                return json(['status'=>200,'msg'=>'接受成功']);
                //=====end===============
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status'=>100,'msg'=>'接受失败，请刷新重试']);
            }
        }
    }


    /**
     * 获取任务详情(这是做任务的详情，不是领任务的详情，首页的领完也是跳到这里)
     * 正常判断之外：如果是分享的分步骤的（task_share_d_fen是2的），根据当前的now_info判断需不需要审核，其他的若task_share_submit为2则无需审核
     */
    public function getTaskInfo(){
        extract(input());
        $where = array();
        $where['tu_id'] = $tu_id;
        //1、任务详情
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where($where)
//            ->field('task_id,task_status,tu_status')
            ->find();
        $sons = array();
        $now_info = array();
        $now_step = 1;
        if($data['task_share_d_fen'] == 2){
            $data = Db::table('up_task_user')->alias('tu')
                ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
                ->where('tu_task_id',$data['task_id'])
                ->where('tu_user_id',$user_id)
                ->order('tu_share_fen DESC')
//            ->field('task_id,task_status,tu_status')
                ->find();
            //此分步骤分享任务的所有步骤
            $sons = Db::table('up_task_fen')
                ->where('tf_task_id',$data['task_id'])
                ->order('tf_order ASC')
                ->select();
            //当前第几步（只要上面的tf_ordre小于此值（不能等于），就说明做过了）$now_step
            //当前步骤的判断依据 $now_step
            if($data['tu_status'] == 2){
                $now_info = array();
                $now_step = 6;
            }else{
                $now_step = $data['tu_share_fen'];
                $now_info = $sons[$now_step-1];
            }

        }
        return json(['status'=>200,'msg'=>$data,'sons'=>$sons,'now_step'=>$now_step,'now_info'=>$now_info]);
    }
    /**
     * 提交任务审核
     */
    public function submitTask()
    {
        extract(input());
        $where = array();
        $where['tu_id'] = $tu_id;
        $task_id = Db::table('up_task_user')->where($where)->value('tu_task_id');
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where('tu_task_id',$task_id)
            ->where('tu_user_id',$user_id)
            ->order('tu_share_fen DESC')
            ->field('tu_id,task_id,task_status,tu_status,task_type,task_share_type,task_share_num,task_share_d_fen,tu_share_fen,task_share_submit,task_share_type,task_share_b_num,tu_share_b_num')
            ->find();
//        $data = Db::table('up_task_user')->alias('tu')
//            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
//            ->where($where)
//            ->field('task_id,task_status,tu_status,task_type,task_share_type,task_share_num')
//            ->find();
        if($data['tu_status'] != 3 && $data['tu_status'] != 4){  //不会有非进行中的任务拒绝后还是拒绝3的状态（是5了）
            return json_encode(['status'=>0,'msg'=>'只有进行中或未通过审核的任务才可以提交']);
        }else{
            if($data['task_type']==1 || $data['task_type']==5 || $data['task_share_submit']==2){ //此值为2时，不可能是分步骤
                return json_encode(['status'=>0,'msg'=>'下载或视频类型的任务不用提交']);
            }else{
                //排除分步骤不用提交的
                if($data['task_share_d_fen'] == 2){
                    $son = Db::table('up_task_fen')
                        ->where('tf_task_id',$data['task_id'])
                        ->where('tf_order',$data['tu_share_fen'])
                        ->find();
                    if($son['tf_submit'] == 2){
                        return json_encode(['status'=>0,'msg'=>'此步骤不需要审核']);
                    }
                }
                //排除曝光率要审核但是不到次数的
                if($data['task_type'] == 6 && $data['task_share_type'] == 1){
                    if($data['task_share_b_num'] > $data['tu_share_b_num']){
                        return json_encode(['status'=>0,'msg'=>'分享次数不够']);
                    }
                }
                $today = date('Y-m-d H:i:s');
                $update = array();
                $update['tu_image'] = trim($image,',');
                $update['tu_submit_time'] = $today;
                $update['tu_status'] = 1;
                $update['tu_real_time'] = $today;
                $update['tu_del'] = 1;
                $res = Db::table('up_task_user')
                    ->where('tu_id',$data['tu_id'])
                    ->update($update);
                if($res){
                    //1、入滚动消息
                    $this->gunNews($user_id,$data['task_id'],1);
                    //1-1：如果是分享的且是曝光率的 // TODO：WHY？？？？
//                    if($data['task_type'] == 6 && $data['task_share_type'] == 1){
//                        Db::name('task')->where('task_id',$data['task_id'])->setInc('task_share_num');
//                    }
                    return json_encode(['status'=>200,'msg'=>'提交成功']);
                }else{
                    return json_encode(['status'=>0,'msg'=>'提交失败']);
                }
            }
        }
    }
    /**
     * 视频和下载的任务完成结算
     * 曝光率的不管要不要审核，分享成功之后调一下这个接口
     */
    public function successTaskTwo()
    {
        extract(input());
        $where = array();
        $where['tu_id'] = $tu_id;
        $task_id = Db::table('up_task_user')->where($where)->value('tu_task_id');
        $fields = 'tu_id,task_id,task_status,tu_status,task_type,task_share_type,task_share_num,task_share_d_fen,tu_share_fen,task_share_submit,task_share_type,task_share_b_num,tu_share_b_num';
        $fields .= ',task_price,task_active,tu_s_id';
        $fields .= ',task_name,task_num,task_done_num';
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where('tu_task_id',$task_id)
            ->where('tu_user_id',$user_id)
            ->order('tu_share_fen DESC')
            ->field($fields)
            ->find();
        $where['tu_id'] = $data['tu_id'];
        if ($data['tu_status'] != 3 && $data['tu_status'] != 4) {
            return json_encode(['status' => 0, 'msg' => '只有进行中或未通过审核的任务才可以提交']);
        } else {
            if ($data['task_type'] != 1 && $data['task_type'] != 5 && $data['task_type'] != 6) {
                return json_encode(['status' => 0, 'msg' => '只有下载或视频类型的任务是自动审核']);
            } else {
                    //-------如果这个任务是分步骤的先改价格----------------------
                    if($data['task_share_d_fen'] == 2){
                        $son = Db::table('up_task_fen')
                            ->where('tf_task_id',$data['task_id'])
                            ->where('tf_order',$data['tu_share_fen'])
                            ->find();
                        if($son['tf_submit'] == 1){
                            return json_encode(['status'=>0,'msg'=>'此步骤需要审核']);
                        }
                        $data['task_price'] = $son['tf_money'];
                    }
                    //-------如果这个任务是不分步骤的得审核----------------------
                    if($data['task_type'] == 6 && $data['task_share_type'] == 2 && $data['task_share_d_fen'] == 1){
                        //如果此任务是需要审核的，则返回
                        if($data['task_share_submit'] == 1){
                            return json_encode(['status'=>0,'msg'=>'此任务需要审核']);
                        }
                    }
                    //-------如果这个任务是曝光率的----------------------
                    if($data['task_type'] == 6 && $data['task_share_type'] == 1){
                        //先把次数加1（我的和此任务的总的）
                        Db::table('up_task_user')->where($where)->setInc('tu_share_b_num',1);
                        Db::name('task')->where('task_id',$data['task_id'])->setInc('task_share_num');
                        if($data['task_share_b_num'] > $data['tu_share_b_num']+1){
                            return json_encode(['status'=>0,'msg'=>'当前分享次数' . ($data['tu_share_b_num']+1)]);
                        }
                        //如果此任务是需要审核的，则返回
                        if($data['task_share_submit'] == 1){
                            return json_encode(['status'=>0,'msg'=>'当前分享次数' . ($data['tu_share_b_num']+1)]);
                        }
                    }
                    Db::startTrans();
                    try {
                    //如果这个任务超时了，48小时内我提交的，因为超时的已经返还了，那要先判断商户有没有这么多钱再抵扣
                    if($data['task_status'] != 2){
                        $mmm = Db::table('up_shops')->where('s_id',$data['tu_s_id'])->value('s_money');
                        if($mmm < $data['task_price']){
                            return json_encode(['status' => 0, 'msg' => '此商户余额不足！']);
                        }else{
                            $tasktype = ['error','下载','求赞求粉','问卷','投票','视频','分享'];
                            Db::name('shops')->where('s_id',$data['tu_s_id'])->setDec ('s_money',$data['task_price']);
                            //入商户明细和商户消息
                            allInShopDetail($data['task_price'],1,$data['tu_s_id'],$tasktype[$data['task_type']].'任务扣除');
                            allInNotice('任务扣除',$tasktype[$data['task_type']].'任务扣除，扣除'.($data['task_price']/10).'元！',3,$data['tu_s_id']);
                        }
                    }
                    //1、先改完成状态
                    $today = date('Y-m-d H:i:s');
                    $update = array();
                    $update['tu_submit_time'] = $today;
                    $update['tu_do_time'] = $today;
                    $update['tu_status'] = 2;
                    $update['tu_real_time'] = $today;
                    Db::table('up_task_user')->where($where)->update($update);
                    //2、改用户余额并入明细
                    if($data['task_active'] == 1){
                        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_all_money',$data['task_price']);
                        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_week_money',$data['task_price']);
                        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_month_money',$data['task_price']);
                    }else{
                        Db::name('u_user')->where('user_id',$user_id)->setInc ('user_active_money',$data['task_price']);//审核通过，用户加钱
                    }
                    allInDetail($user_id,1,'任务',$data['task_price'],$data['task_type'],$data['task_active']);
                    //3、改商家完成数：
                    if($data['task_share_d_fen'] == 2){
                        //先加分步骤的钱数
                        Db::table('up_task')->where('task_id',$data['task_id'])->setInc('task_share_d_fen_money',$data['task_price']);
                        if($data['tu_share_fen'] <= 1){ //不管分享分不分步骤，只要此值小于1，加就是
                            Db::table('up_task')->where('task_id',$data['task_id'])->setInc('task_done_num',1);
                        }
                        $allsteps = Db::table('up_task_fen')->where('tf_task_id',$data['task_id'])->count();
                        if($data['tu_share_fen'] < $allsteps){
                            $insert = array();
                            $insert['tu_number'] = time() . rand(10,99);
                            $insert['tu_task_id'] = $task_id;
                            $insert['tu_s_id'] = $data['tu_s_id'];
                            $insert['tu_user_id'] = $user_id;
                            $insert['tu_image'] = '';
                            $insert['tu_receive_time'] = $today;
                            $insert['tu_submit_time'] = '';
                            $insert['tu_cancel_time'] = '';
                            $insert['tu_do_time'] = '';
                            $insert['tu_reason'] = '';
                            $insert['tu_status'] = 4;
                            $insert['tu_real_time'] = $today;
                            //大富要的
                            $insert['tu_date'] = date('Y-m-d');
                            $insert['tu_hour'] = date('Y-m-d H');
                            $insert['tu_type'] = $data['task_type'];
                            $insert['tu_task_active'] = $data['task_active'];
                            $insert['tu_share_fen'] = $data['tu_share_fen']+1;
                            Db::table('up_task_user')->insert($insert);
                        }
                    }else{
                        Db::table('up_task')->where('task_id',$data['task_id'])->setInc('task_done_num',1);
                    }
                    Db::commit();
                    //完成提醒
                    if ($data['task_done_num']+1 >= $data['task_num']) {
                        allInNotice('任务完成提示', '尊敬的商户您好，您发布的 ' . $data['task_name'] . ' 任务已经完成！', 3, $data['tu_s_id']);
                    }
                    //1、入滚动消息----------------------------------------------------
                    $this->gunNews($user_id,$data['task_id'],2);
                    return json_encode(['status' => 200, 'msg' => '成功']);
                    //=====end===============
                } catch (\Exception $e) {
                    Db::rollback();
                    return json_encode(['status' => 0, 'msg' => '失败']);
                }
            }
        }
    }
    /**
     * 取消任务
     */
    public function receiveTask(){
        extract(input());
        $where = array();
        $where['tu_id'] = $tu_id;
        //1、任务详情
        $task_id = Db::table('up_task_user')->where($where)->value('tu_task_id');
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where('tu_task_id',$task_id)
            ->where('tu_user_id',$user_id)
            ->order('tu_share_fen DESC')
            ->field('tu_id,task_id,task_status,tu_status,tu_share_fen,tu_super_yes,tu_task_active')
            ->find();
        if($data){
            if($data['tu_task_active'] == 3 && $data['tu_super_yes'] == 2){
                return json(['status'=>0,'msg'=>'达人任务一旦接受不可取消！']);
            }
            if($data['task_status'] != 1 && $data['task_status'] != 2){
                return json(['status'=>0,'msg'=>'此任务已下架或者已结束，不可取消']);
            }elseif ($data['tu_status'] != 3 && $data['tu_status'] != 4){
                return json(['status'=>0,'msg'=>'只有进行中或审核被拒的任务才可以取消']);
            }else{
                $today = date('Y-m-d H:i:s');
                $update = array();
                $update['tu_status'] = 6;
                $update['tu_cancel_time'] = $today;
                if($data['tu_task_active'] == 3 && $data['tu_super_yes'] == 1){
                    $update['tu_super_yes'] = 3;
                }
                $res = Db::table('up_task_user')->where('tu_id',$data['tu_id'])->update($update);
                if($res){
                    //领取任务量减1(特殊：分步骤的分享任务第二步之前减去)
                    if($data['tu_share_fen'] <= 1){
                        Db::table('up_task')->where('task_id',$data['task_id'])->setDec('task_get_num');
                    }
                    return json(['status'=>200,'msg'=>'取消成功']);
                }else{
                    return json(['status'=>0,'msg'=>'取消失败']);
                }
            }
        }else{
            return json(['status'=>0,'msg'=>'已经没有此任务了']);
        }
    }
    /**
     * 投诉任务
     */
    public function complainTask()
    {
        extract(input());
        $where = array();
        $where['tu_id'] = $tu_id;
        //1、任务详情
        $data = Db::table('up_task_user')->alias('tu')
            ->join('up_task t','tu.tu_task_id=t.task_id','LEFT')
            ->where($where)
            ->field('task_id,task_status,task_s_id,task_status')
            ->find();
        if($data){
            if($data['task_status'] == 4 || $data['task_status'] == 5){
                return json(['status'=>0,'msg'=>'此任务已下架或者已被删除']);
            }else{
                $today = date('Y-m-d H:i:s');
                $insert = array();
                $insert['complain_user_id'] = $user_id;
                $insert['complain_task_id'] = $data['task_id'];
                $insert['complain_content'] = $content;
                if(isset($image)){
                    $insert['complain_img'] = trim($image,',');
                }
                $insert['complain_time'] = $today;
                $insert['complain_shop_id'] = $data['task_s_id'];
                $res = Db::table('up_complain')->insert($insert);
                if($res){
                    return json(['status'=>200,'msg'=>'投诉成功']);
                }else{
                    return json(['status'=>0,'msg'=>'投诉失败']);
                }
            }
        }else{
            return json(['status'=>0,'msg'=>'已经没有此任务了']);
        }
    }

    /**
     * 入滚动消息表
     * @param $user_id
     * @param $task_id
     * @param $type：1是需要提交审核的，2是不需要提交审核的（直接就获取奖励了）
     * @return bool
     */

    public function gunNews($user_id,$task_id,$type)
    {
        $str = ['未知', '下载', '求赞求粉','问卷','投票','视频','分享'];
        $task = Db::table('up_task')->where('task_id',$task_id)->field('task_type,task_price')->find();
        $uname = Db::table('up_u_user')->where('user_id',$user_id)->value('user_username');
        $a = mb_substr( $uname, 0, 1,'utf-8' );
        $b = mb_substr( $uname, -1, 1,'utf-8' );
        if($type == 1){
            $title = "{$a}***{$b}领取了{$str[$task['task_type']]}任务;";
        }else{
            $title = "{$a}***{$b}完成了{$str[$task['task_type']]}任务，获得{$task['task_price']}个云币;";
        }
        $data = [
            'gun_user_id'=>$user_id,
            'gun_task_id'=>$task_id,
            'gun_title'=>$title,
            'gun_time'=>date('Y-m-d H:i:s')
        ];
        Db::table('up_gun_news')->insert($data);
        return true;
    }

}